﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using log4net;
using Mangox.Model.MyBusinessDB;
using Mangox.Common;
using System.Diagnostics;
using Mangox.Model.Stock;

namespace Mangox.BLL.Applet
{
    /// <summary>
    /// 用户操作
    /// 增删改查案例，示例
    /// </summary>
    public class UserBLL
    {
        protected static ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        private static string className = (new StackTrace()).GetFrame(1).GetMethod().ReflectedType.Name + "/";

        public List<User> GetUserList()
        {
            List<User> list = null;
            using (MyBusinessDBContext dbContext = new MyBusinessDBContext())
            {
                list = dbContext.Users.ToList();

                //var list2 = dbContext.Users.Where(u => u.Id < 3);//延迟查询
                //var list4 = list2.Where(u => u.Name.Length < 3).OrderBy(u => u.Id);

                //var list3 = dbContext.Users.Where(u => u.Id < 3).ToList();
            }

            return list;
        }

        public User GetUser(string openid)
        {
            User user = null;
            using (MyBusinessDBContext dbContext = new MyBusinessDBContext())
            {
                //这种写法openid必须是主键，否则会报错
                //user = dbContext.User.Find(openid);

                var tempList = dbContext.Users.Where(u => u.Openid == openid).ToList() as List<User>;
                if (tempList != null && tempList.Count > 0)
                {
                    user = tempList[0];
                }
            }
            return user;
        }

        public bool AddUser(WxLoginParam model)
        {
            try
            {
                log.Info($"添加用户信息-{JsonCommon.ToJson(model)}");

                using (MyBusinessDBContext dbContext = new MyBusinessDBContext())
                {
                    var temp = new User()
                    {
                        Openid = model.openid,
                        Session_key = model.session_key,
                        UnionId = model.unionid,
                        CreateTime = DateTime.Now,
                        LoginTime = DateTime.Now,
                        LastLoginTime = DateTime.Now,
                        LoginCount = 1
                    };

                    dbContext.Users.Add(temp);
                    return dbContext.SaveChanges() > 0;
                }
            }
            catch (Exception ex)
            {
                log.ErrorFormat(className + "AddUser fail-{0}", ex);
            }
            return false;
        }

        /// <summary>
        /// 必须先查询出来再赋值更新，必须是当前dbContext，不能些两个方法的dbContext
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public bool UpdateUser(WxLoginParam model)
        {
            try
            {
                using (MyBusinessDBContext dbContext = new MyBusinessDBContext())
                {
                    var list = dbContext.Users.Where(u => u.Openid == model.openid).ToList() as List<User>;
                    if (list.Count <= 0)
                    {
                        return false;
                    }

                    User us = list[0];
                    if (us == null)
                    {
                        return false;
                    }

                    us.Session_key = model.session_key;
                    us.UnionId = model.unionid;
                    us.LastLoginTime = DateTime.Now;
                    us.LoginCount = ++us.LoginCount;

                    return dbContext.SaveChanges() > 0;
                }
            }
            catch (Exception ex)
            {
                log.ErrorFormat(className + "UpdateUser fail-{0}", ex);
            }
            return false;
        }


        public User UpdateAuthUser(WxAuthParam param)
        {
            User us = null;
            try
            {
                using (MyBusinessDBContext dbContext = new MyBusinessDBContext())
                {

                    us = (dbContext.Users.Where(u => u.Openid == param.openid).ToList() as List<User>)[0];

                    us.IsAuth = 1;
                    us.NickName = param.nickName;
                    us.Gender = param.gender;
                    us.Language = param.language;
                    us.City = param.city;
                    us.Province = param.city;
                    us.Country = param.country;
                    us.AvatarUrl = param.avatarUrl;

                    if (dbContext.SaveChanges() > 0)
                    {
                        log.ErrorFormat(className + "UpdateAuthUser {0}授权成功，NickName-{1}", param.openid, us.NickName);
                        return us;
                    }
                }
            }
            catch (Exception ex)
            {
                log.ErrorFormat(className + "UpdateAuthUser fail-{0}", ex);
            }
            return us;
        }

        public bool DelUser(User user)
        {
            using (MyBusinessDBContext dbContext = new MyBusinessDBContext())
            {
                dbContext.Users.Remove(user);
                return dbContext.SaveChanges() > 0;
            }
        }








    }
}
